package com.sh.shanhuo.activity;


import android.content.Intent;
import android.net.sip.SipProfile;
import android.net.sip.SipSession;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.sh.shanhuo.R;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.bean.SyncDataBean;
import com.sh.shanhuo.bean.UploadImageBean;
import com.sh.shanhuo.database.SQLDBUtils;
import com.sh.shanhuo.database.sort.SortInfoDBUtils;
import com.sh.shanhuo.database.sort.SortInfoDatabase;
import com.sh.shanhuo.database.sort.SortInfoEntity;
import com.sh.shanhuo.database.web.WebInfoDBUtils;
import com.sh.shanhuo.database.web.WebInfoDatabase;
import com.sh.shanhuo.database.web.WebInfoEntity;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.Tools;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.sqlite.db.SupportSQLiteDatabase;
import okhttp3.Call;

public class CloudActivity extends BaseActivity {
    private String appUserName;
    private TextView uploadTips;
    private TextView downloadTips;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_cloud;
    }

    @Override
    protected void initView() {
        super.initView();
        getBundle();
        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> finish());
        LinearLayout upload = findViewById(R.id.upload);
        LinearLayout download = findViewById(R.id.download);
        uploadTips = findViewById(R.id.uploadTips);
        downloadTips = findViewById(R.id.downloadTips);
        upload.setOnClickListener(v -> uploadWebInfo());
        download.setOnClickListener(v -> load());
    }

    private void getBundle() {
        Intent intent = getIntent();
        if (intent == null)
            return;
        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;
        appUserName = bundle.getString("appUserName", "");
    }

    private void uploadWebInfo() {
        uploadTips.setVisibility(View.VISIBLE);
        uploadTips.setText("上传中...");
        Message msg = new Message();
        msg.what = 100;
        SupportSQLiteDatabase database = WebInfoDatabase.getDatabase();
        try {
            database.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(() ->
                OkHttpUtil.getInstance().postDBFile(OkHttpUtil.IP + OkHttpUtil.UPLOAD_IMAGE, database.getPath(), new GsonObjectCallback<UploadImageBean>() {
                    @Override
                    public void onUi(UploadImageBean uploadImageBean) {
                        if (uploadImageBean.getCode() == 200 && !TextUtils.isEmpty(uploadImageBean.getUrl())) {
                            uploadSortInfo(msg, uploadImageBean.getUrl());
                        } else {
                            msg.arg1 = 2;
                            handler.sendMessage(msg);
                        }
                    }

                    @Override
                    public void onFailed(Call call, IOException e) {
                        msg.arg1 = 2;
                        handler.sendMessage(msg);
                    }
                })).start();

    }

    private void uploadSortInfo(Message msg, String webInfoUrl) {
        SupportSQLiteDatabase database = SortInfoDatabase.getDatabase();
        try {
            database.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(() -> OkHttpUtil.getInstance().postDBFile(OkHttpUtil.IP + OkHttpUtil.UPLOAD_IMAGE, database.getPath(), new GsonObjectCallback<UploadImageBean>() {
            @Override
            public void onUi(UploadImageBean uploadImageBean) {
                if (uploadImageBean.getCode() == 200 && !TextUtils.isEmpty(uploadImageBean.getUrl())) {
                    commit(msg, webInfoUrl, uploadImageBean.getUrl());
                } else {
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
            }
        })).start();

    }

    private void commit(Message msg, String webInfoUrl, String sortInfoUrl) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", appUserName);
        params.put("content", webInfoUrl + "," + sortInfoUrl);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.UPLOAD_MSG, params, new GsonObjectCallback<BaseBean>() {
            @Override
            public void onUi(BaseBean baseBean) {
                if (baseBean.getCode() == 200) {
                    msg.arg1 = 1;
                } else {
                    msg.arg1 = 2;
                }
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(Call call, IOException e) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
            }
        });
    }

    private void load() {
        downloadTips.setVisibility(View.VISIBLE);
        downloadTips.setText("下载中...");
        Map<String, String> params = new HashMap<>();
        params.put("userName", appUserName);
        Message msg = new Message();
        msg.what = 101;
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.DOWNLOAD_MSG, params, new GsonObjectCallback<SyncDataBean>() {
            @Override
            public void onUi(SyncDataBean syncDataBean) {
                if (syncDataBean.getCode() == 200 && syncDataBean.getData() != null) {
                    downloadWebInfo(msg, syncDataBean.getData().getContent());
                } else {
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
            }
        });
    }

    private void downloadWebInfo(Message msg, String url) {
        String downloadPath = Tools.getBaseCachePath(CloudActivity.this) + "database/sync_web_database";
        FileUtils.createOrExistsFile(downloadPath);
        String webInfoUrl = url.substring(0, url.indexOf(","));
        String sortInfoUrl = url.substring(url.indexOf(",") + 1);
        new Thread(() -> OkHttpUtil.getInstance().download(webInfoUrl, downloadPath, new SipSession.Listener() {
            @Override
            public void onRinging(SipSession session, SipProfile caller, String sessionDescription) {
                WebInfoDBUtils.deleteAll(CloudActivity.this);
                List<WebInfoEntity> webInfoEntities = SQLDBUtils.getWebInfoDB(sessionDescription);
                for (WebInfoEntity webInfoEntity : webInfoEntities) {
                    WebInfoDBUtils.insertWebInfo(CloudActivity.this, webInfoEntity);
                }
                downloadSortInfo(msg, sortInfoUrl);
                super.onRinging(session, caller, sessionDescription);
            }

            @Override
            public void onError(SipSession session, int errorCode, String errorMessage) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
                super.onError(session, errorCode, errorMessage);
            }
        })).start();
    }

    private void downloadSortInfo(Message msg, String url) {
        String downloadPath = Tools.getBaseCachePath(CloudActivity.this) + "database/sync_sort_database";
        FileUtils.createOrExistsFile(downloadPath);
        new Thread(() -> OkHttpUtil.getInstance().download(url, downloadPath, new SipSession.Listener() {
            @Override
            public void onRinging(SipSession session, SipProfile caller, String sessionDescription) {
                SortInfoDBUtils.deleteAll(CloudActivity.this);
                List<SortInfoEntity> sortInfoEntities = SQLDBUtils.getSortDB(sessionDescription);
                for (SortInfoEntity sortInfoEntity : sortInfoEntities) {
                    SortInfoDBUtils.insertSortInfo(CloudActivity.this, sortInfoEntity);
                }
                msg.arg1 = 1;
                handler.sendMessage(msg);
                super.onRinging(session, caller, sessionDescription);
            }

            @Override
            public void onError(SipSession session, int errorCode, String errorMessage) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
                super.onError(session, errorCode, errorMessage);
            }
        })).start();
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 100) {
                if (msg.arg1 == 1)
                    uploadTips.setText("上传完毕");
                if (msg.arg1 == 2)
                    uploadTips.setText("上传失败");
            }
            if (msg.what == 101) {
                if (msg.arg1 == 1)
                    downloadTips.setText("下载完毕");
                if (msg.arg1 == 2)
                    downloadTips.setText("下载失败");
            }
            return false;
        }
    });
}
